package com.relytosoft.mizar.media.display.services.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.relytosoft.dubhe.common.api.entity.system.SysFile;
import com.relytosoft.dubhe.common.api.service.RemoteFileService;
import com.relytosoft.dubhe.common.core.object.ResponseResult;
import com.relytosoft.dubhe.common.log.annotation.OpLog;
import com.relytosoft.dubhe.common.log.enums.OpTypeEnum;
import com.relytosoft.dubhe.common.redis.utils.RedisUtil;
import com.relytosoft.dubhe.common.satoken.entity.CurrentUser;
import com.relytosoft.mizar.media.common.constant.MediaCommonConstants;
import com.relytosoft.mizar.media.common.enums.UpLoadFileEnum;
import com.relytosoft.mizar.media.common.utils.ImageUtil;
import com.relytosoft.mizar.media.display.api.entity.VideoConfig;
import com.relytosoft.mizar.media.display.api.pojo.query.ChannelPlayDetailQuery;
import com.relytosoft.mizar.media.display.api.pojo.vo.VideoChannelVo;
import com.relytosoft.mizar.media.display.api.pojo.vo.VideoPlayVo;
import com.relytosoft.mizar.media.display.services.service.VideoService;
import com.relytosoft.mizar.media.external.api.display.request.ManualVideoDto;
import com.relytosoft.mizar.media.external.api.display.request.ReplayTheaterDto;
import com.relytosoft.mizar.media.external.api.display.response.VideoClipInfoDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 视频查看
 *
 * @Author SunLi
 * @Date: 2022/4/18 11:45
 * @Version 1.0
 */
@Validated
@RestController
@RequestMapping("/display/video")
@Api(tags = "视频查看相关接口")
public class VideoController {

    @Resource
    private VideoService videoService;

    @Resource
    private RemoteFileService remoteFileService;

    @GetMapping(value = "/channellist")
    @ApiOperation("获得通道列表")
    public ResponseResult<List<VideoChannelVo>> selectVideoChannelList(@ApiParam("区域ID") @RequestParam(required = false) Integer districtId, @ApiParam("名称") @RequestParam(required = false) String name) {
        return ResponseResult.ok(videoService.selectVideoChannelList(districtId, name));
    }

    @GetMapping(value = "/channeltreelist")
    @ApiOperation("获得通道列表树")
    public ResponseResult<List<Tree<Integer>>> selectVideoChannelTreeList(@ApiParam("区域ID") @RequestParam(required = false) Integer districtId, @ApiParam("名称") @RequestParam(required = false) String name) {
        return ResponseResult.ok(videoService.buildVideoChannelListTree(videoService.selectVideoChannelList(districtId, name)));
    }

    @PutMapping(value = "/getplayurl")
    @ApiOperation("获得通道播放URL")
    @OpLog(msg = "视频查看", opType = OpTypeEnum.OTHER)
    public ResponseResult<List<VideoPlayVo>> selectPlayUrl(@ApiParam("通道") @RequestBody List<ChannelPlayDetailQuery> channelPlayDetailList) {
        List<VideoPlayVo> rotaPlayVoList = videoService.buildPlayStreamUrl(channelPlayDetailList);
        return ResponseResult.ok(rotaPlayVoList);
    }

    @SaCheckPermission("display:video:replayTheater")
    @OpLog(msg = "录像回放", opType = OpTypeEnum.OTHER)
    @ApiOperation("录像回放")
    @PostMapping("/playback/{channelId}")
    public ResponseResult<VideoClipInfoDto> replayTheater(@RequestBody ReplayTheaterDto replayTheaterDto, @PathVariable String channelId) {
        VideoClipInfoDto videoClipInfoDto = videoService.buildReplayTheaterStreamUrl(replayTheaterDto, channelId);
        return ResponseResult.ok(videoClipInfoDto);
    }

    @SaCheckPermission("display:video:manualVideo")
    @OpLog(msg = "手动录像", opType = OpTypeEnum.OTHER)
    @ApiOperation("手动录像")
    @PostMapping("/manual/video")
    public ResponseResult<Map<String, String>> manualVideo(@RequestBody ManualVideoDto manualVideoDto) {
        return ResponseResult.ok(videoService.manualVideo(manualVideoDto));
    }

    @SaCheckPermission("display:video:stopManualVideo")
    @OpLog(msg = "停止录像", opType = OpTypeEnum.OTHER)
    @ApiOperation("停止录像")
    @PostMapping("/stop/video")
    public ResponseResult<Void> stopManualVideo(@RequestBody List<Map<String, Object>> map) {
        String msg = videoService.stopManualVideo(map);
        return ResponseResult.ok(msg);
    }

    @ApiOperation("关断流")
    @GetMapping("close")
    public ResponseResult<Void> closeStream(@RequestParam("playStreamKey") String playStreamKey) {
        videoService.closeStream(playStreamKey);
        return ResponseResult.ok();
    }


    @PutMapping(value = "/manualcapture")
    @ApiOperation("手动抓图")
    public ResponseResult manualCapture(@ApiParam("通道") @RequestParam("channelIndexCode") String channelIndexCode) {
        try {
            if (StrUtil.isEmpty(channelIndexCode)) {
                return ResponseResult.fail("通道号为空！");
            }
            String url = videoService.manualCapture(channelIndexCode);
            if (StrUtil.isEmpty(url)) {
                return ResponseResult.fail("抓图失败！");
            }
            //图片Url转byte[]
            byte[] imgByte = ImageUtil.trustUrlToBytes(url);
            //获取用户设置的初始目录
            String filePath=getFilePath();
            String content_type="image/jpeg";
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
            String fileName = LocalDateTime.now().format(dtf)+".jpg";
            SysFile sysFile = remoteFileService.upload("", fileName, content_type, imgByte, UpLoadFileEnum.SCREEN_SHOT.getCode());
            Map<String, String> map = new HashMap(3);
            map.put("url", sysFile.getUrl());
            map.put("filePath", filePath);
            map.put("fileName", fileName);
            return ResponseResult.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }
    }

    private String getFilePath() {
        //获取用户设置信息
        VideoConfig videoConfig = null;
        if (RedisUtil.hasKey(MediaCommonConstants.CACHE_USERVIDEOCONFIG + CurrentUser.getCurrentUserId())) {
            String data = RedisUtil.get(MediaCommonConstants.CACHE_USERVIDEOCONFIG + CurrentUser.getCurrentUserId()).toString();
            videoConfig = JSONObject.parseObject(data, VideoConfig.class);
        }else {
            videoConfig = new VideoConfig();
            videoConfig.setUserId(CurrentUser.getCurrentUserId());
            videoConfig.setSavePath("c:\\mizar-media\\Pictures");
            videoConfig.setPhotoFormat(1000);
            RedisUtil.set(MediaCommonConstants.CACHE_USERVIDEOCONFIG + CurrentUser.getCurrentUserId(), JSON.toJSONString(videoConfig), 3600L);
        }
        return videoConfig.getSavePath();
    }
}
